import React from 'react';
import { WeaAvatar, WeaInputSearch, WeaLocaleProvider, WeaScroll, WeaTop } from 'ecCom';
import { observer } from 'mobx-react';
import { Col, Dropdown, Icon, Menu, Row, Tabs, Tree } from 'antd';
import isEqual from 'lodash/isEqual';
import { removeHTMLTag } from '../../util';
import $ from "jquery";
import _ from 'lodash';
const TreeNode = Tree.TreeNode;
const getLabel = WeaLocaleProvider.getLabel;

const TabPane = Tabs.TabPane;
const getKeys = datas => datas.map(data => data.domid);

// 获取总数，和每一叉树的所有 key
const getAllKeys = datas => {
    let num = datas.length;
    let keys = getKeys(datas);
    const childs = datas.map(data => {
        const obj = {
            domid: data.domid,
            childs: [] as any[],
            keys: [] as any[],
            num: 0
        };
        if (data.childs && data.childs.length > 0) {
            const _obj = getAllKeys(data.childs);
            num += _obj.num;
            obj.num = _obj.num;
            obj.childs = [..._obj.childs];
            obj.keys = [..._obj.keys];
            keys = keys.concat(_obj.keys);
        }
        return obj;
    });
    return {
        num,
        childs,
        keys,
    };
};

// 添加节点是否可展开标识，即是否有子集
const addLeaf = datas => datas.map(data => {
    const _data = { ...data };
    if (data.childs && data.childs.length > 0) {
        _data.isLeaf = false;
        _data.childs = addLeaf(data.childs);
    } else if (data.haschild) {
        _data.isLeaf = false;
    } else {
        _data.isLeaf = true;
    }
    return _data;
});

// 获取 maxLev 级树的数据
const getDefautDatasShow = (datas) => (
    datas.map(data => {
        const _data = { ...data };
        if (_data.childs && _data.childs.length > 0) {
            _data.childs = getDefautDatasShow(data.childs);
        }
        return _data;
    })
);

// 点击展开节点，添加当前节点子集数据
const getDatasShow = (datas, datashow, domid) => datashow.map((data, index) => {
    const _data = { ...data };
    if (_data.domid === domid) {
        let _childs = [...datas[index].childs];
        _childs = _childs.map(c => {
            const _c = { ...c };
            _c.childs = [];
            return _c;
        });
        _data.childs = _childs;
    } else if (datas[index].childs && datas[index].childs.length > 0) {
        _data.childs = getDatasShow(datas[index].childs, _data.childs, domid);
    }
    return _data;
});

// 过滤搜索值
const filterDatas = (datas, v) => datas.map(data => {
    const _data = { ...data };
    if (data.name.indexOf(v) >= 0 || (data.ecologyPinyinSearch && data.ecologyPinyinSearch.indexOf(v) >= 0)) {
        const _childs = data.childs ? [...data.childs] : [];
        _data.isFind = true;
        _data.childs = _childs;
    } else if (data.childs && data.childs.length > 0) {
        const childs = filterDatas(data.childs, v);
        const _childs = childs.filter(c => c.isFind);
        if (_childs.length === 0) {
            _data.isFind = false;
        } else {
            _data.isFind = true;
            _data.childs = childs;
        }
    } else {
        _data.isFind = false;
    }
    return _data;
}).filter(c => c.isFind);

// 点击收藏 更改收藏状态
const doFavEdit = (datas, domid) => datas.map(data => {
    const _data = { ...data };
    if (data.domid === domid) {
        _data.fav = !_data.fav;
    } else if (data.childs && data.childs.length > 0) {
        _data.childs = doFavEdit(data.childs, domid);
    }
    return _data;
});

// 删除不包含收藏节点的子集
const doNoFavDelete = datas => datas.map(data => {
    const _data = { ...data };
    _data.hasChildFav = false;
    if (data.childs && data.childs.length > 0) {
        const childs = doNoFavDelete(data.childs);
        const _childs = childs.filter(c => c.fav || c.hasChildFav);
        if (_childs.length > 0) {
            _data.hasChildFav = true;
            _data.childs = _childs;
        } else {
            _data.isLeaf = true;
            _data.childs = [];
        }
    }
    return _data;
}).filter(c => c.fav || c.hasChildFav);

export interface LeftTreeProps {
    onSelect?: Function;
    datas: any[];
    topName: string | HTMLElement;
    expandedKeys?: string[];
    selectedKeys?: string[];
    counts?: any;
    countsType?: any;
    showCollect?: boolean;
    loading?: boolean;
    onCollect?: Function;
    onlyShowFav?: boolean;
    onFliterAll?: Function;
    loadData?: Function;
    onNodeClick?: Function;
    expandFirstNode?: number;
    hasQuickSearch?: boolean;
    onQuickSearch?: (search: string) => void;
    onExpandChange?: (expandedKeys: string[]) => void;
    onChangeTree?:(tree)=>void;
    combintreeway:any;
    combintree:any;
    currentTree:string;
}



@observer
export default class LeftTree extends React.Component<LeftTreeProps, any> {
    isMounted: boolean;
    constructor(props) {
        super(props);
        const { datas = [], selectedKeys = [] } = props;
        const _datas = addLeaf(datas);
        const datasShow = getDefautDatasShow(_datas);
        this.isMounted = false;
        this.state = {
            height: 0,
            datas: _datas,
            datasShow,
            selectedKeys,
            topName: props.topName || ""
        };
    }
    componentDidMount() {
        this.isMounted = true;
        this.scrollheigth();
        $(window).resize(() => {
            this.isMounted && this.scrollheigth();
        });
    }
    scrollheigth = () => {
        const top = $('.wea-new-tree .wea-new-tree-scroll').offset()
            ? ($('.wea-new-tree .wea-new-tree-scroll').offset().top
                ? $('.wea-new-tree .wea-new-tree-scroll').offset().top : 0) : 0;
        // @ts-ignore
        const scrollheigth = document.documentElement.clientHeight - top - 15;
        $('.wea-new-tree .wea-new-tree-scroll').height(scrollheigth);
    }
    componentWillReceiveProps(nextProps) {
        const { datas = [], selectedKeys = [], topName = "" } = this.props;
        const _selectedKeys = nextProps.selectedKeys || [];
        const _datas = nextProps.datas || [];
        if (!isEqual(datas, _datas)) {
            const __datas = addLeaf(_datas);
            let datasShow = getDefautDatasShow(__datas);
            this.setState({ datas: __datas, datasShow });
        }
        if (!isEqual(selectedKeys, _selectedKeys)
            && !isEqual(this.state.selectedKeys, _selectedKeys)) {
            this.setState({ selectedKeys: _selectedKeys });
        }
        if (!isEqual(topName, nextProps.topName)) {
            this.setState({ topName: nextProps.topName });
        }
    }
    shouldComponentUpdate(nextProps, nextState) {
        return !isEqual(this.state.selectedKeys, nextState.selectedKeys) ||
            !isEqual(this.props.selectedKeys, nextProps.selectedKeys) ||
            !isEqual(this.props.datas, nextProps.datas) ||
            !isEqual(this.props.counts, nextProps.counts) ||
            !isEqual(this.props.countsType, nextProps.countsType) ||
            this.props.loading !== nextProps.loading ||
            !isEqual(this.props.expandedKeys, nextProps.expandedKeys) ||
            !isEqual(this.state.datasShow, nextState.datasShow) ||
            !isEqual(this.state.topName, nextState.topName) ||
            this.state.height !== nextState.height;
    }
    componentDidUpdate() {
        this.scrollheigth();

    }
    componentWillUnmount() {
        this.isMounted = false;
    }
    onFliterAll() {
        if (typeof this.props.onFliterAll === 'function') {
            this.props.onFliterAll();
        }
    }
    onExpandChange = (expandedKeys, ) => {
        this.setState({ expandedKeys });
        this.props.onExpandChange && this.props.onExpandChange(expandedKeys);
    }

    onChangeTree = (treeid ) => {
        this.refs.inputsearch['clear']&&this.refs.inputsearch['clear']();
        this.props.onChangeTree && this.props.onChangeTree(treeid);
    }

    onSelect = (keys, { node }) => {
        if (this.props.onNodeClick && node && node.props && node.props.eventKey) {
            this.props.onNodeClick(node.props.eventKey);
        }
        let key = node.props.eventKey
        if (keys.indexOf(key) < 0) {
            keys.push(key);
        }
        this.setState({ selectedKeys: keys });
        if (typeof (this.props.onSelect) === 'function') {
            this.props.onSelect(key,node.props);
        }
    }
    onLoadData = (node) => {
        return new Promise((resolve) => {
            if (this.props.loadData && node && node.props && node.props.eventKey) {
                this.props.loadData(node.props.eventKey,node.props, () => {
                    resolve();
                })
            }
        })
    }
    getTitle = (data) => {
        const style = { width: 16, height: 16, border: 'none', verticalAlign: 'middle', marginTop: -3, marginRight: 2 };
        if(data.hrmtype&&data.hrmtype=='resource'){
            let hrmid=data.key.replace(/^\d+_/,'');
            return [<WeaAvatar // url加载失败显示默认处理
                        userId={hrmid}
                        style={{lineHeight:'normal', ...style}}
                    />,
                    <span title={removeHTMLTag(data.name)}>{data.name}</span>]
        }
        return (
            [(data.img || data.icon) && <button style={data.img ? { background: `url(${data.img}) 0 0 no-repeat`, backgroundSize: '16px 16px', ...style } : style} >{data.icon && <i className={data.icon} />}</button>,
            <span title={removeHTMLTag(data.name)}>{data.name}</span>]
        )
    }
    renderTreeNodes = (datas: any[] = [], counts = {}, countsType, lev) => {
        const newDatas = [] as any[];
        datas && datas.forEach(data => {
            const { childs = [] as any[] } = data;
            newDatas.push(
                <TreeNode
                    browserTree={true}
                    key={data.domid}
                    data={data}
                    isLeaf={data.isLeaf}
                    title={this.getTitle(data)}
                    level={lev}
                >
                    {this.renderTreeNodes(childs, counts, countsType, lev + 1)}
                </TreeNode>
            );
        });
        return newDatas;
    }
    render() {
        const {combintree,combintreeway } = this.props;
        const { topName } = this.state;
        return (
            <div className="cube-tree-list">
                {combintree&&combintree.length<=1&&
                    <WeaTop
                    title={topName}
                    icon={<i className="icon-mode-org" />}
                    buttons={[]}
                    >
                        {this.getBaseTree()}
                    </WeaTop>
                }
                {combintree&&combintree.length>1&&combintreeway=='0'&&//下拉
                <div>{this.getDropMenu()}{this.getBaseTree()}</div>
                }
                {combintree&&combintree.length>1&&combintreeway=='1'&&//平铺
                <div>{this.getTabMenu()}{this.getBaseTree()}</div>
                 }
            </div>
        )
    }

    //平铺显示
    getTabMenu=()=>{
        const { combintree = [], currentTree } = this.props;
        if (_.isEmpty(combintree)) return;

        return <Tabs defaultActiveKey={currentTree} onChange={this.onChangeTree}>
            {combintree.map(item => <TabPane
                tab={<div title={item.name} className='cube-tree-list-tab'>{item.name}</div>}
                key={item.companyid}/>)
            }
        </Tabs>;
    }



    //下拉显示
    getDropMenu =()=>{
        const {combintree,currentTree } = this.props;
        let showName = "";
        const menuItem :any= [];
        combintree.forEach(item => {
            menuItem.push(
              <Menu.Item key={item.companyid} title={item.name}>
                {item.name}
              </Menu.Item>
            );
            menuItem.push(<Menu.Divider />);
            if (item.companyid === currentTree) {
              showName = item.name;
            }
          });
        const typeMenu = (
            <Menu
              className="wea-browser-drop-menu max-height-large"
              onSelect={(node)=>this.onChangeTree(node.key)}
              selectedKeys={[currentTree]}
            >
              {menuItem}
            </Menu>
          );

        return <div className={`wea-drop-menu cube-tree-menu`}style={{ width: "100%",display:'block' }}>
                <Row>
                <Col span={24}>
                    <Dropdown overlay={typeMenu} trigger={["click"]}>
                    <a style={{height:47,lineHeight:'47px'}} className="ant-dropdown-link text-elli pr25">
                        <i className={"icon-mode-org"} />
                        <span title={showName  || ""}>
                        {showName  || null}{" "}
                        </span>
                        <Icon type="down" className="icon-down" />
                    </a>
                    </Dropdown>
                </Col>
                </Row>
            </div>
    }


    getBaseTree = ()=>{
        const { counts, countsType, hasQuickSearch, expandedKeys } = this.props;
        const { datasShow = [], selectedKeys } = this.state;
        let style=hasQuickSearch?{}:{display:'none'};
        return  <div className='wea-new-tree'>
        <div className='wea-input-wraper wea-left-tree-search wea-cube-left-tree'  style={style}>
            <div className="wea-input-focus">
                <WeaInputSearch  ref="inputsearch"
                    style={{ width: '100%' }}
                    className="cubeTree-InputSearch"
                    placeholder={getLabel(83788,"请输入关键字搜索")}
                    onSearch={this.props.onQuickSearch}
                />
            </div>
        </div>
        <WeaScroll className='wea-new-tree-scroll' typeClass='scrollbar-macosx'>
            {
                <Tree
                    className="wea-left-tree-antd"
                    autoExpandParent={false}
                    expandedKeys={expandedKeys}
                    onExpand={this.onExpandChange}
                    onSelect={this.onSelect}
                    selectedKeys={selectedKeys}
                    loadData={this.onLoadData}
                >
                    {this.renderTreeNodes(datasShow, counts, countsType, 0)}
                </Tree>
            }
        </WeaScroll>
    </div>
    }
}